package task.manager.view;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import task.manager.R;
import task.manager.model.Task;
import task.manager.model.TaskApplication;
import task.manager.model.ValidateText;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.*;

// TODO: Auto-generated Javadoc
/**
 * The Class AddNewTask.
 */
public class AddNewTask extends Activity {

	/** The cancel add task. */
	Button addTask, cancelAddTask;
	
	/** The description. */
	EditText task, location, date, description;
	
	/** The type. */
	String type;
	
	/** The date. */
	Date theDate;

	/** The new year. */
	private int newYear;
	
	/** The new month. */
	private int newMonth;
	
	/** The new day. */
	private int newDay;
	
	/** The error msg. */
	private TextView errorMsg;
	
	/** The category. */
	private Spinner category;
	
	/** The array category. */
	private String[] arrayCategory = { "Personal", "School", "Work" };

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addnewitem);
		setTitle("Add Task");
		addTask = (Button) findViewById(R.id.bAddTask);
		cancelAddTask = (Button) findViewById(R.id.bCancelAddTask);
		task = (EditText) findViewById(R.id.tNewTask);
		location = (EditText) findViewById(R.id.tLocation);
		date = (EditText) findViewById(R.id.tDuedate);
		description = (EditText) findViewById(R.id.tdescription);
		errorMsg = (TextView) findViewById(R.id.tAddTaskErrorMsg);
		//type = (EditText) findViewById(R.id.tCategory);

		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(
				AddNewTask.this, android.R.layout.simple_spinner_item,
				arrayCategory);
		category = (Spinner) findViewById(R.id.spinner1);
		category.setAdapter(categoryAdapter);
		category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				type = arrayCategory[pos];
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		cancelAddTask.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		addTask.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				ValidateText validate = new ValidateText();
				if(task.getText().toString().isEmpty()){
					errorMsg.setText("Please enter a task name.");
					errorMsg.setTextColor(Color.RED);
				}
				else if(!validate.isDateValid(date.getText().toString())){
					errorMsg.setText("Date is not valid.");
					errorMsg.setTextColor(Color.RED);
				}else{
				Intent resultIntent = new Intent();
				TaskApplication facade = TaskApplication.getInstance();
				LinkedList<Task> tasks = facade.getTaskList();
				theDate = new Date(newYear, newMonth, newDay);
				tasks.add(new Task(task.getText().toString(), location
						.getText().toString(), theDate, description.getText()
						.toString(), type));
				LinkedList<Task> list = facade.getCurrentUser().sortTaskList();
				facade.getCurrentUser().setTaskList(list);
				try {
					facade.saveBinary();
				} catch (Exception e) {
					e.printStackTrace();
				}
				setResult(Activity.RESULT_OK, resultIntent);
				finish();
				}
			}
		});

		date.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					showDialog(0);
				}
				return false;
			}
		});

		date.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showDialog(0);
				} else {
					dismissDialog(0);
				}
			}
		});

		final Calendar c = Calendar.getInstance();
		newYear = c.get(Calendar.YEAR);
		newMonth = c.get(Calendar.MONTH);
		newDay = c.get(Calendar.DAY_OF_MONTH);

		// updateDate();

	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		super.onCreateDialog(id);
		DatePickerDialog dateDlg = new DatePickerDialog(this,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						newYear = year;
						newMonth = monthOfYear;
						newDay = dayOfMonth;
						updateDate();

					}
				}, newYear, newMonth, newDay);
		return dateDlg;
	}

	/**
	 * Update date.
	 */
	private void updateDate() {
		date.setText(new StringBuilder().append(newMonth + 1).append("/")
				.append(newDay).append("/").append(newYear).append(" "));
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	protected void onPause() {
		super.onPause();
		finish();
	}
}
